﻿using AutoMapper;
using MediatR;
using Traceability.Commont.Domains;
using Traceability.Commont.DTOs.CommontFiles;
using Traceability.Commont.DTOs.UsersFile;
using Traceability.Commont.Infrastructures.Interfaces;

namespace Traceability.Api.Applications.Userss
{
    public class UserListHander : IRequestHandler<UserListCommand, PageDTO<UserListDTO>>
    {
        public readonly IBateRepository<Users> user;
        public readonly IBateRepository<Roles> roles;
        public readonly IBateRepository<UserRoles> userroles;
        public readonly IMapper mapper;

        public UserListHander(IBateRepository<Users> user, IBateRepository<Roles> roles, IBateRepository<UserRoles> userroles, IMapper mapper)
        {
            this.user = user;
            this.roles = roles;
            this.userroles = userroles;
            this.mapper = mapper;
        }

        public async Task<PageDTO<UserListDTO>> Handle(UserListCommand request, CancellationToken cancellationToken)
        {
            PageDTO<UserListDTO> res = new PageDTO<UserListDTO>() { totalCount=0,pageCount=0};
            var list = (from a in user.GetAll()
                        join b in userroles.GetAll() on a.UserId equals b.UserId
                        join c in roles.GetAll() on b.RolesId equals c.RolesId
                        select new UserListDTO
                        {
                            UserId=a.UserId,
                            UserName=a.UserName,
                            Pwd=a.Pwd,
                            Stuct=a.Stuct,
                            CreateTime = a.CreateTime,
                            RolesName=c.RolesName
                        }).ToList();
            if (!string.IsNullOrEmpty(request.UserName))
            {
                list = list.Where(x => x.UserName.Contains(request.UserName)).ToList();
            }
            res.totalCount = list.Count;
            res.pageCount =(int) Math.Ceiling(res.totalCount * 1.0 / request.pageSize);
            list = list.OrderBy(x => x.UserId).Skip((request.pageIndex - 1) * request.pageSize).Take(request.pageSize).ToList();
            res.Lists= list;
            return res;
        }
    }
}
